import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Slider } from './ui/slider';
import { Heart, Clock, Trophy, Star, Eye, Users, Mic, Smile } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';
import { EmotionResponse, EmotionAnalysis } from '../types/emotionRecognition';
import { 
  EMOTION_SCENARIOS, 
  EMOTION_CATEGORIES, 
  EMOTION_NAMES, 
  CONTEXT_DESCRIPTIONS 
} from '../constants/emotionRecognition';

interface EmotionRecognitionTestProps {
  onComplete: (result: TestResult) => void;
}

export function EmotionRecognitionTest({ onComplete }: EmotionRecognitionTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'confidence' | 'results'>('instructions');
  const [currentStimulus, setCurrentStimulus] = useState(0);
  const [selectedStimuli, setSelectedStimuli] = useState<any[]>([]);
  const [selectedEmotion, setSelectedEmotion] = useState<string>('');
  const [confidence, setConfidence] = useState<number[]>([3]);
  const [responses, setResponses] = useState<EmotionResponse[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [stimulusStartTime, setStimulusStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [feedbackMessage, setFeedbackMessage] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const TOTAL_STIMULI = 15;

  // 智能选择刺激材料 - 修复答案打乱问题
  const selectStimuli = () => {
    const shuffled = [...EMOTION_SCENARIOS].sort(() => Math.random() - 0.5);
    
    // 确保各种类型都有代表，平衡分布
    const stimuliByType: { [key: string]: any[] } = {
      facial_expression: [],
      body_language: [],
      voice_tone: [],
      social_scenario: [],
      micro_expression: []
    };
    
    // 按类型分组，确保每种类型至少有2个
    shuffled.forEach(stimulus => {
      if (stimuliByType[stimulus.type].length < 3) {
        stimuliByType[stimulus.type].push(stimulus);
      }
    });
    
    // 收集选中的刺激
    const selected: any[] = [];
    Object.values(stimuliByType).forEach(typeStimuli => {
      selected.push(...typeStimuli);
    });
    
    // 如果不够15个，按难度平衡补充
    if (selected.length < TOTAL_STIMULI) {
      const remaining = shuffled.filter(s => !selected.includes(s));
      const difficultyBalance = {
        easy: Math.ceil((TOTAL_STIMULI - selected.length) * 0.4),
        medium: Math.ceil((TOTAL_STIMULI - selected.length) * 0.4),
        hard: Math.floor((TOTAL_STIMULI - selected.length) * 0.2)
      };
      
      ['easy', 'medium', 'hard'].forEach(difficulty => {
        const diffItems = remaining.filter(s => s.difficulty === difficulty);
        selected.push(...diffItems.slice(0, difficultyBalance[difficulty as keyof typeof difficultyBalance]));
      });
    }

    // 最终随机打乱，并为每个刺激打乱选项
    return selected.slice(0, TOTAL_STIMULI).map(stimulus => ({
      ...stimulus,
      options: [...stimulus.options].sort(() => Math.random() - 0.5) // 打乱选项顺序
    })).sort(() => Math.random() - 0.5);
  };

  // 分析混淆矩阵
  const analyzeConfusionMatrix = (responses: EmotionResponse[]) => {
    const matrix: { [key: string]: { [key: string]: number } } = {};
    
    responses.forEach(response => {
      const stimulus = selectedStimuli.find(s => s.id === response.stimulusId);
      if (!stimulus) return;
      
      const actual = EMOTION_NAMES[stimulus.emotion as keyof typeof EMOTION_NAMES];
      const predicted = response.selectedEmotion;
      
      if (!matrix[actual]) matrix[actual] = {};
      if (!matrix[actual][predicted]) matrix[actual][predicted] = 0;
      matrix[actual][predicted]++;
    });
    
    return matrix;
  };

  // 分析各类型准确率
  const analyzeTypeAccuracy = (responses: EmotionResponse[]) => {
    const typeStats: { [key: string]: { correct: number; total: number } } = {};
    
    responses.forEach(response => {
      const stimulus = selectedStimuli.find(s => s.id === response.stimulusId);
      if (!stimulus) return;
      
      const type = CONTEXT_DESCRIPTIONS[stimulus.type as keyof typeof CONTEXT_DESCRIPTIONS];
      if (!typeStats[type]) typeStats[type] = { correct: 0, total: 0 };
      
      typeStats[type].total++;
      if (response.correct) typeStats[type].correct++;
    });
    
    const result: { [key: string]: number } = {};
    Object.entries(typeStats).forEach(([type, stats]) => {
      result[type] = stats.total > 0 ? (stats.correct / stats.total) * 100 : 0;
    });
    
    return result;
  };

  useEffect(() => {
    if (stage === 'test' && selectedStimuli.length > 0) {
      setStimulusStartTime(Date.now());
    }
  }, [currentStimulus, stage]);

  const handleStartTest = () => {
    const stimuli = selectStimuli();
    setSelectedStimuli(stimuli);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleEmotionSelect = (emotion: string) => {
    setSelectedEmotion(emotion);
    setStage('confidence');
  };

  const handleConfidenceSubmit = () => {
    if (!selectedEmotion || isSubmitting) return;
    
    setIsSubmitting(true);
    
    const stimulus = selectedStimuli[currentStimulus];
    const reactionTime = Date.now() - stimulusStartTime;
    const correctEmotion = EMOTION_NAMES[stimulus.emotion as keyof typeof EMOTION_NAMES];
    const isCorrect = selectedEmotion === correctEmotion;
    
    const response: EmotionResponse = {
      stimulusId: stimulus.id,
      selectedEmotion,
      correct: isCorrect,
      reactionTime,
      confidence: confidence[0],
      stimulusType: stimulus.type,
      difficulty: stimulus.difficulty
    };
    
    setResponses(prev => [...prev, response]);
    
    if (isCorrect) {
      setScore(prev => prev + 1);
    }
    
    // 立即切换到测试阶段显示反馈
    setStage('test');
    
    // 显示反馈
    setFeedbackCorrect(isCorrect);
    setFeedbackMessage(
      isCorrect 
        ? `正确！这确实表达了"${correctEmotion}"` 
        : `错误！正确答案是"${correctEmotion}"，您选择的是"${selectedEmotion}"`
    );
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      setSelectedEmotion('');
      setConfidence([3]);
      setIsSubmitting(false);
      
      if (currentStimulus < selectedStimuli.length - 1) {
        setCurrentStimulus(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, 1200); // 缩短反馈时间到1.2秒
  };

  const handleComplete = () => {
    const totalStimuli = selectedStimuli.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalStimuli) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    
    // 分析情绪识别能力
    const basicEmotions = responses.filter(r => {
      const stimulus = selectedStimuli.find(s => s.id === r.stimulusId);
      return stimulus && EMOTION_CATEGORIES.basic.includes(stimulus.emotion);
    });
    
    const complexEmotions = responses.filter(r => {
      const stimulus = selectedStimuli.find(s => s.id === r.stimulusId);
      return stimulus && EMOTION_CATEGORIES.complex.includes(stimulus.emotion);
    });
    
    const microExpressions = responses.filter(r => r.stimulusType === 'micro_expression');
    
    const analysis: EmotionAnalysis = {
      overallAccuracy: accuracy,
      basicEmotionAccuracy: basicEmotions.length > 0 ? 
        Math.round((basicEmotions.filter(r => r.correct).length / basicEmotions.length) * 100) : 0,
      complexEmotionAccuracy: complexEmotions.length > 0 ? 
        Math.round((complexEmotions.filter(r => r.correct).length / complexEmotions.length) * 100) : 0,
      microExpressionAccuracy: microExpressions.length > 0 ? 
        Math.round((microExpressions.filter(r => r.correct).length / microExpressions.length) * 100) : 0,
      averageReactionTime: Math.round(responses.reduce((sum, r) => sum + r.reactionTime, 0) / responses.length),
      averageConfidence: Math.round((responses.reduce((sum, r) => sum + r.confidence, 0) / responses.length) * 10) / 10,
      emotionConfusionMatrix: analyzeConfusionMatrix(responses),
      strengthsByType: analyzeTypeAccuracy(responses),
      weaknessesByType: {}
    };

    // 按刺激类型统计
    const typeStats: { [key: string]: { correct: number; total: number; avgTime: number; avgConf: number } } = {};
    
    responses.forEach(response => {
      const stimulus = selectedStimuli.find(s => s.id === response.stimulusId);
      if (!stimulus) return;
      
      const type = CONTEXT_DESCRIPTIONS[stimulus.type as keyof typeof CONTEXT_DESCRIPTIONS];
      if (!typeStats[type]) {
        typeStats[type] = { correct: 0, total: 0, avgTime: 0, avgConf: 0 };
      }
      
      typeStats[type].total++;
      if (response.correct) typeStats[type].correct++;
      typeStats[type].avgTime += response.reactionTime;
      typeStats[type].avgConf += response.confidence;
    });

    // 计算平均值
    Object.keys(typeStats).forEach(type => {
      const stats = typeStats[type];
      stats.avgTime = Math.round(stats.avgTime / stats.total);
      stats.avgConf = Math.round((stats.avgConf / stats.total) * 10) / 10;
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'emotion-recognition',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalStimuli,
        correctAnswers,
        accuracy,
        basicEmotionAccuracy: analysis.basicEmotionAccuracy,
        complexEmotionAccuracy: analysis.complexEmotionAccuracy,
        microExpressionAccuracy: analysis.microExpressionAccuracy,
        averageReactionTime: analysis.averageReactionTime,
        averageConfidence: analysis.averageConfidence,
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type,
          accuracy: stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
          correct: stats.correct,
          total: stats.total,
          avgReactionTime: stats.avgTime,
          avgConfidence: stats.avgConf
        })),
        emotionConfusionMatrix: analysis.emotionConfusionMatrix,
        stimuliUsed: selectedStimuli.map(s => s.id)
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-pink-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Heart className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">情绪识别测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您识别和理解他人情绪的能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-pink-50 to-rose-50 rounded-xl p-6 border border-pink-100">
              <h3 className="font-semibold text-pink-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察各种情绪表达的描述或情境</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>识别表达的具体情绪类型</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>评估您对答案的置信度</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>包含面部表情、身体语言、微表情等多种类型</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <Eye className="w-4 h-4" />
                  面部表情
                </h4>
                <p className="text-sm text-blue-700">识别面部情绪表达</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <Users className="w-4 h-4" />
                  身体语言
                </h4>
                <p className="text-sm text-green-700">理解肢体动作情绪</p>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <Mic className="w-4 h-4" />
                  语音语调
                </h4>
                <p className="text-sm text-purple-700">分析声音中的情绪</p>
              </div>
              <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-4 border border-orange-200">
                <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
                  <Smile className="w-4 h-4" />
                  社交情境
                </h4>
                <p className="text-sm text-orange-700">理解情境中的情绪</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-pink-100 rounded-xl border border-pink-200">
                <div className="text-2xl font-bold text-pink-600 mb-1">25+</div>
                <div className="text-sm text-pink-700">情绪场景</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
                <div className="text-2xl font-bold text-rose-600 mb-1">15</div>
                <div className="text-sm text-rose-700">随机选择</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-rose-50 rounded-xl border border-pink-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">多维</div>
                <div className="text-sm text-slate-700">情绪分析</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始情绪识别
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && selectedStimuli.length > 0) {
    const stimulus = selectedStimuli[currentStimulus];
    const progress = (currentStimulus / selectedStimuli.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 即时反馈提示 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-sm"
            >
              <Card className={`border-0 shadow-xl ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-4 px-6">
                  <div className="text-center">
                    <div className="font-semibold mb-2 text-lg">
                      {feedbackCorrect ? '✓ 正确！' : '✗ 错误！'}
                    </div>
                    <div className="text-sm opacity-90">
                      {feedbackMessage}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>

        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-pink-100 text-pink-700 border-pink-300">
              情境 {currentStimulus + 1} / {selectedStimuli.length}
            </Badge>
            <Badge variant="outline" className={`${
              stimulus.type === 'facial_expression' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              stimulus.type === 'body_language' ? 'bg-green-100 text-green-700 border-green-300' :
              stimulus.type === 'voice_tone' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              stimulus.type === 'social_scenario' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              'bg-red-100 text-red-700 border-red-300'
            }`}>
              {CONTEXT_DESCRIPTIONS[stimulus.type as keyof typeof CONTEXT_DESCRIPTIONS]}
            </Badge>
            <Badge variant="outline" className={`${
              stimulus.difficulty === 'easy' ? 'bg-green-100 text-green-700 border-green-300' :
              stimulus.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              'bg-red-100 text-red-700 border-red-300'
            }`}>
              {stimulus.difficulty === 'easy' ? '简单' :
               stimulus.difficulty === 'medium' ? '中等' : '困难'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 情境描述 */}
        <Card className="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg text-slate-800">情绪识别</CardTitle>
              {stimulus.context && (
                <Badge variant="secondary" className="text-xs">
                  情境：{stimulus.context}
                </Badge>
              )}
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-slate-50 to-gray-50 rounded-xl p-6 border border-slate-200">
              <p className="text-lg text-slate-800 leading-relaxed text-center">
                {stimulus.description}
              </p>
            </div>

            <div>
              <h4 className="text-md font-semibold text-slate-700 mb-4 text-center">
                这个人表达的是什么情绪？
              </h4>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {stimulus.options.map((option: string, index: number) => (
                  <motion.div
                    key={index}
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                  >
                    <Button
                      variant={selectedEmotion === option ? "default" : "outline"}
                      onClick={() => handleEmotionSelect(option)}
                      className={`w-full h-auto min-h-[3rem] text-center ${
                        selectedEmotion === option 
                          ? 'bg-gradient-to-r from-pink-600 to-rose-500 text-white border-pink-600' 
                          : 'hover:bg-pink-50 hover:border-pink-300 text-slate-700'
                      }`}
                    >
                      <span className={selectedEmotion === option ? 'text-white' : 'text-slate-800'}>
                        {option}
                      </span>
                    </Button>
                  </motion.div>
                ))}
              </div>
            </div>

            {stimulus.intensity && (
              <div className="text-center text-sm text-slate-600">
                强度提示：{stimulus.intensity === 'low' ? '轻微' : 
                        stimulus.intensity === 'medium' ? '中等' : '强烈'}
              </div>
            )}
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'confidence') {
    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto space-y-6"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-lg text-slate-800 text-center">
              置信度评估
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center">
              <p className="text-slate-700 mb-2">您选择的情绪是：</p>
              <div className="text-2xl font-bold text-pink-600 mb-6">
                {selectedEmotion}
              </div>
            </div>

            <div className="space-y-4">
              <p className="text-center text-slate-700">
                您对这个答案有多大把握？
              </p>
              <div className="px-4">
                <div className="relative emotion-confidence-slider">
                  <Slider
                    value={confidence}
                    onValueChange={setConfidence}
                    max={5}
                    min={1}
                    step={1}
                    className="w-full"
                  />
                  {/* 置信度标记 */}
                  <div className="flex justify-between mt-2 px-1">
                    {[1, 2, 3, 4, 5].map((level) => (
                      <div
                        key={level}
                        className={`text-xs font-semibold transition-colors duration-200 ${
                          confidence[0] >= level 
                            ? 'text-pink-600' 
                            : 'text-slate-400'
                        }`}
                      >
                        {level}
                      </div>
                    ))}
                  </div>
                  {/* 置信度描述 */}
                  <div className="text-center mt-2">
                    <span className="text-sm text-slate-600">
                      {confidence[0] === 1 ? '完全不确定' :
                       confidence[0] === 2 ? '不太确定' :
                       confidence[0] === 3 ? '一般确定' :
                       confidence[0] === 4 ? '比较确定' : '非常确定'}
                    </span>
                  </div>
                </div>
                <div className="flex justify-between text-sm text-slate-600 mt-3">
                  <span>完全不确定</span>
                  <span>非常确定</span>
                </div>
                <div className="text-center mt-4">
                  <Badge variant="outline" className="bg-gradient-to-r from-pink-100 to-rose-100 text-pink-700 border-pink-300">
                    <Star className="w-3 h-3 mr-1" />
                    置信度：{confidence[0]} / 5
                  </Badge>
                </div>
              </div>
            </div>

            <Button
              onClick={handleConfidenceSubmit}
              disabled={isSubmitting}
              className="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 disabled:from-pink-400 disabled:to-rose-400 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105 active:scale-95 disabled:scale-100"
              size="lg"
            >
              <span className="flex items-center gap-2">
                {isSubmitting ? '正在提交...' : '确认提交'}
                {isSubmitting ? (
                  <motion.div
                    animate={{ rotate: 360 }}
                    transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                  >
                    <Star className="w-4 h-4" />
                  </motion.div>
                ) : (
                  <Star className="w-4 h-4" />
                )}
              </span>
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalStimuli = selectedStimuli.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalStimuli) * 100);
    const averageConfidence = responses.reduce((sum, r) => sum + r.confidence, 0) / responses.length;
    const averageReactionTime = responses.reduce((sum, r) => sum + r.reactionTime, 0) / responses.length;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-pink-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-pink-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-pink-600 to-rose-500 bg-clip-text text-transparent">
              {accuracy}
            </div>
            <p className="text-slate-600">情绪识别准确率</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-pink-100 rounded-xl border border-pink-200">
                <div className="text-2xl font-bold text-pink-600 mb-1">{correctAnswers}/{totalStimuli}</div>
                <div className="text-sm text-pink-700">正确识别</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200">
                <div className="text-2xl font-bold text-rose-600 mb-1">
                  {Math.round(averageConfidence * 10) / 10}
                </div>
                <div className="text-sm text-rose-700">平均置信度</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">
                  {Math.round(averageReactionTime / 1000)}s
                </div>
                <div className="text-sm text-purple-700">平均反应</div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>


      </motion.div>
    );
  }

  return null;
}